import { RoleIsSuper } from './DatabaseType/Role';
import type { UserRecord } from './DatabaseType/User';

type AccessCollection = {
  [key: string | symbol | number]: boolean;
};

/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */
export default function access(
  initialState: { currentUser?: UserRecord } | undefined,
) {
  const { currentUser } = initialState ?? {};

  const permissionResource = currentUser?.permissionList?.reduce(
    (prevResult, currentPermission) => {
      prevResult[currentPermission.name] = true;
      return prevResult;
    },
    {} as AccessCollection,
  );

  const proxy = new Proxy(permissionResource || {}, {
    get(target, property) {
      // 如果是超管直接跳过，访问任何属性都返回true
      if (currentUser?.roles.some((role) => role.isSuper === RoleIsSuper.Yes)) {
        return true;
      }
      return target[property];
    },
  });

  return proxy;
}
